import axios from 'axios';
import * as API from '../constants/api';
import { TOKEN_KEY } from '../constants/conf';
import { Message } from 'element-ui';
import { goTo } from './';

const request = axios.create({
  baseURL: API.BASE_URL,
  timeout: 5000,
});

request.interceptors.request.use((conf) => {
  conf.headers = {
    ...conf.headers,
    ...getCommonHeaders(),
  };
  return conf;
});

request.interceptors.response.use(

  // success
  (res) => {
    const { data } = res;
    if (!data.success) {
      return Promise.reject(data);
    }
    return data.data;
  },

  // fail
  (err) => {
    // log error info dir warn time
    if (err.response.status === 401) {
      Message.warning(API.LOGIN_ERR_MSG);
      setTimeout(() => {
        goTo('/login');
      }, 1000);
    }
    return Promise.reject(err);
  },

);

export default request;

export function createRequestPromise (urlKey, data, method = 'get') {
  const requestConfig = {
    url: API[urlKey], // key name
    method, // GET POST get post
  };
  switch (method.toLowerCase()) {
    case 'get':
      requestConfig.params = data;
      break;
    case 'post':
      requestConfig.data = data;
      break;
    // more methods here
    default:
      break;
  }
  return request(requestConfig);
}

export function getCommonHeaders () {
  return {
    Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
  };
}
